package com.lmx.project.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.lmx.project.common.BaseResponse;
import com.lmx.project.common.ErrorCode;
import com.lmx.project.common.ResultUtils;
import com.lmx.project.exception.BusinessException;
import com.lmx.project.model.dto.resourse.ResourseAddRequest;
import com.lmx.project.model.dto.resourse.ResourseQueryRequest;
import com.lmx.project.model.dto.resourse.ResourseUpdateRequest;
import com.lmx.project.model.entity.Label;
import com.lmx.project.model.entity.Resourse;
import com.lmx.project.model.vo.ResourseVo;
import com.lmx.project.model.vo.UsersVo;
import com.lmx.project.service.LabelService;
import com.lmx.project.service.ResourseService;
import com.lmx.project.service.UsersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;
import java.util.function.Consumer;

/**
 * @author lmx
 * 本类负责有关资源的的增删改查
 */
@RestController
@RequestMapping("/resourse")
@Slf4j
public class ResourseController {
    @Resource
    private ResourseService resourseService;


    @Resource
    private UsersService usersService;


    private String resoursedir = "resourse/";

    @Resource
    private ComfileController comfileController;

//
    @Resource
    private LabelService labelService;

    /**
     * 增加记录
     */
    @PostMapping
    public BaseResponse<Long> addResourse(@RequestBody ResourseAddRequest resourseAddRequest, HttpServletRequest request) throws IOException {
        if (resourseAddRequest.getTitle() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "资源标题为空");
        }

        if (resourseAddRequest.getContent() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "资源内容为空");
        }

        if (resourseAddRequest.getStatu() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "资源状态为空");
        }

//        如果状态是1 但是列表是空
        if (resourseAddRequest.getStatu() == 1 && (resourseAddRequest.getFileIdlist() == null
                || resourseAddRequest.getFileIdlist().isEmpty())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "资源文件列表为空");
        }

        if (resourseAddRequest.getLablelist() == null || resourseAddRequest.getLablelist().size() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "资源标签为空");
        }


//        判断该标签是否在标签表中

        for (String s : resourseAddRequest.getLablelist()) {
            LambdaQueryWrapper<Label> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Label::getName, s);
            Label one = labelService.getOne(queryWrapper);
            if (one == null) {
                Label entity = new Label();
                entity.setName(s);
                labelService.save(entity);
            }
        }


//        BaseResponse<Users> usersByid = usersController.getUsersByid(request);
//
//        if (usersByid.getData() == null) {
//            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR, "请先登录");
//        }

        Resourse resourse = new Resourse();
        Gson gson = new Gson();

        if (resourseAddRequest.getStatu() == 1) {
            String s = gson.toJson(resourseAddRequest.getFileIdlist());
            resourse.setFileIdlist(s);
        }

        BeanUtils.copyProperties(resourseAddRequest, resourse);
//        resourse.setUserid(usersByid.getData().getId());
//        BaseResponse<Users> usersByid = usersController.getUsersByid(request);
        UsersVo data = usersService.getUserCurrent(request);
        if (data == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }

        resourse.setUserid(data.getId());
        String s1 = gson.toJson(resourseAddRequest.getLablelist());
        resourse.setLablelist(s1);

        boolean save = resourseService.save(resourse);

        if (save) {
            return ResultUtils.success(resourse.getId());
        } else {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "请联系管理员或稍后再试");
        }
    }


    /**
     * 删除记录
     */
    @DeleteMapping()
    public BaseResponse<Boolean> deleteResourse(Long id) throws IOException {

        if (id == null || id == 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "id不能为空");
        }

        Resourse byId = resourseService.getById(id);
        if (byId == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "该资源不存在");
        }

//    先删除资源
        Gson gson = new Gson();
        if (byId.getStatu() == 1) {
            String fileIdlist = byId.getFileIdlist();
            List<Long> longs = (List<Long>) gson.fromJson(fileIdlist, new TypeToken<List<Long>>() {
            }.getType());
            comfileController.DeleteFile(longs);
//            String fileurllist = byId.getFileurllist();
//            List<String> fileList = (List<String>) gson.fromJson(fileurllist, new TypeToken<List<String>>() {
//            }.getType());
//
//            for (String s : fileList) {
//                String[] split = s.split("/");
//                String key = split[split.length - 2] + "/" + split[split.length - 1];
//                boolean deletefile = fileUntil.deletefile(key);
//                if (!deletefile) {
//                    log.info("图片删除失败");
//                }
//            }
        }

//        删除数据库中的记录
        boolean b = resourseService.removeById(id);
        if (b) {
            return ResultUtils.success(b);
        } else {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "请联系管理员或稍后重试");
        }
    }

    /**
     * 修改记录
     */
    @PutMapping
    public BaseResponse<Boolean> UpdateResourse(ResourseUpdateRequest resourseUpdateRequest, HttpServletRequest request) throws IOException {

        if (resourseUpdateRequest.getId() == null || resourseUpdateRequest.getId() == 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "id不能为空");
        }
//        if (resourseUpdateRequest.getStatu()==1 && (resourseUpdateRequest.getFileIdlist()==null ||resourseUpdateRequest.getFileIdlist().size()==0)){
//            throw new BusinessException(ErrorCode.PARAMS_ERROR,"资源列表为空");
//        }

        if (resourseUpdateRequest.getLablelist() != null) {
            //        判断该标签是否在标签表中,如果没有则在label中加入记录
            for (String s : resourseUpdateRequest.getLablelist()) {
                LambdaQueryWrapper<Label> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(Label::getName, s);
                Label one = labelService.getOne(queryWrapper);
                if (one == null) {
                    Label entity = new Label();
                    entity.setName(s);
                    labelService.save(entity);
                }
            }
        }


        Resourse byId = resourseService.getById(resourseUpdateRequest.getId()); //原有的记录
        Gson gson = new Gson();
        Resourse resourse = new Resourse();
        BeanUtils.copyProperties(resourseUpdateRequest, resourse);

        if (resourseUpdateRequest.getStatu() == 1 && resourseUpdateRequest.getFileIdlist() != null) {
//            删除表中的原有记录
            String fileIdlist = byId.getFileIdlist();
            List<Long> longs = (List<Long>) gson.fromJson(fileIdlist, new TypeToken<List<Long>>() {
            }.getType());
            comfileController.DeleteFile(longs);
//            替换原有资源

            List<Long> fileIdlist1 = resourseUpdateRequest.getFileIdlist();
            String s = gson.toJson(fileIdlist1);

            resourse.setFileIdlist(s);
        }


        boolean b = resourseService.updateById(resourse);
        if (b) {
            return ResultUtils.success(b);
        } else {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "请联系管理员或稍后重试");
        }


    }

    /**
     * 获取项目
     * */
    @GetMapping()
    public BaseResponse<ResourseVo> getResourseByid(Long id){
        if (id==null || id==0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Resourse byId = resourseService.getById(id);
        if (byId==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        ResourseVo resourseVo = new ResourseVo();
        BeanUtils.copyProperties(byId,resourseVo);
        if (byId.getStatu()==1){
            String fileIdlist = byId.getFileIdlist();
            Gson gson = new Gson();
            List<Long> longs = (List<Long>) gson.fromJson(fileIdlist, new TypeToken<List<Long>>() {
            }.getType());
            resourseVo.setFileIdlist(longs);
        }


        return ResultUtils.success(resourseVo);
    }


    /**
     * 分页获取资源列表
     */
    @PostMapping("list")
    public BaseResponse<Page<Resourse>> getResourseList(@RequestBody ResourseQueryRequest resourseQueryRequest) {

        LambdaQueryWrapper<Resourse> queryWrapper = new LambdaQueryWrapper<>();

//        根据用户id获取
        if (resourseQueryRequest.getUserid()!=null && resourseQueryRequest.getUserid()!=0){
            queryWrapper.eq(Resourse::getUserid,resourseQueryRequest.getUserid());
        }

        if (resourseQueryRequest.getText() != null && !resourseQueryRequest.getText().equals("")) {
            queryWrapper.like(Resourse::getTitle, resourseQueryRequest.getText())
                    .or().like(Resourse::getContent, resourseQueryRequest.getText())
            ;
        }

//        标签列表
        if (resourseQueryRequest.getLableList() != null && !resourseQueryRequest.getLableList().isEmpty()) {
            List<String> lableList = resourseQueryRequest.getLableList();
            for (String s : lableList) {
                queryWrapper.and(new Consumer<LambdaQueryWrapper<Resourse>>() {
                    @Override
                    public void accept(LambdaQueryWrapper<Resourse> resourseLambdaQueryWrapper) {
                        resourseLambdaQueryWrapper.like(Resourse::getLablelist, s);
                    }
                });
            }
        }
        queryWrapper.orderByDesc(Resourse::getCreatedtime);
        Page<Resourse> page = resourseService.page(new Page<Resourse>(resourseQueryRequest.getCurrent(), resourseQueryRequest.getPageSize()), queryWrapper);
        return ResultUtils.success(page);
    }

}